#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# File: data_download.py
# Date: 2024/7/4
# Author: 抖音、快手、视频号：东哥策略交易，微信：dongtrader
# Description: 东哥量化，带你走上量化之路。


from get_stock_data import *
import json

# pandas 打印显示设置
pd.set_option('display.width', None)  # 自动调整列宽
pd.set_option('display.max_columns', None)  # 显示所有列
pd.set_option('display.max_rows', None)  # 显示所有行


def show_data(num=-1, codes=None):
    def Writejson(code):
        try:
            df = feather.read_dataframe(f'{stockpath}/{code}.feather')
            # 打印显示
            print(df[-10:])
            # 转为csv文件，用excle打开查看。
            # df.to_csv(f'{stockpath}/{code}.csv', index=False)
        except Exception as e:
            print(f'没有找到{code}股票数据, 错误代码为：{e}')


    if codes is None:
        stock_codes = get_filenames_in_directory(stockpath)
        if num == -1:
            # 获取所有股票数据表名称
            stock_codes = stock_codes
        else:
            stock_codes = stock_codes[:num]

        for code in stock_codes:
            Writejson(code)
    else:
        if type(codes) == str:
            Writejson(codes)
        elif type(codes) == list:
            for code in codes:
                Writejson(code)


def inquire_code(factor, num=-1):
    # 获取所有股票数据表名称
    stock_codes = get_filenames_in_directory(stockpath)
    random.shuffle(stock_codes)
    result_df = pd.DataFrame()
    list = stock_codes[:num]
    stock_num = len(list)
    print(f'统计股票数量：{int(stock_num)}个,加载数据中；')
    for code in tqdm(list):
        df = feather.read_dataframe(f'{stockpath}/{code}.feather')
        # 提取最后一行
        last_row = df.iloc[-1:]
        # 将这一行添加到结果 DataFrame 中
        result_df = pd.concat([result_df, last_row], ignore_index=True)
    Label = factor
    # print(result_df[-10:])

    trades = result_df[f'{Label}_trades'].sum()
    success = result_df[f'{Label}_success'].mean()
    earnings = result_df[f'{Label}_earnings'].mean()
    maxsuccess = result_df[f'{Label}_success'].max()
    minsuccess = result_df[f'{Label}_success'].min()
    maxearnings = result_df[f'{Label}_earnings'].max()
    minearnings = result_df[f'{Label}_earnings'].min()
    maxprofit = result_df[f'{Label}_maxprofit'].max()
    maxdrawdown = result_df[f'{Label}_maxdrawdown'].min()
    winstreak = result_df[f'{Label}_winstreak'].max()
    losestreak = result_df[f'{Label}_losestreak'].max()
    profitstreak = result_df[f'{Label}_profitstreak'].max()
    drawdownstreak = result_df[f'{Label}_drawdownstreak'].min()
    fac_dict = {}
    fac_list = [maxsuccess, minsuccess, maxearnings, minearnings, maxprofit, maxdrawdown, winstreak, losestreak,
                profitstreak, drawdownstreak]
    Label_list = ['success', 'success', 'earnings', 'earnings','maxprofit', 'maxdrawdown', 'winstreak', 'losestreak',
                'profitstreak', 'drawdownstreak']
    key_list = ['maxsuccess', 'minsuccess', 'maxearnings', 'minearnings', 'maxprofit', 'maxdrawdown', 'winstreak', 'losestreak',
                  'profitstreak', 'drawdownstreak']
    for i in range(len(fac_list)):

        df_code = result_df.loc[result_df[f'{Label}_{Label_list[i]}'] == fac_list[i], 'code'].values.tolist()[0]

        fac_df = feather.read_dataframe(f'{stockpath}/{df_code}.feather')
        date = fac_df.loc[fac_df[f'{Label}_{Label_list[i]}'] == fac_list[i], 'date'].values.tolist()[0]

        first_matching_index = fac_df.index[fac_df[f'{Label}_{Label_list[i]}'] == fac_list[i]].min()
        holddate = fac_df.loc[first_matching_index - 1, f'{Label}_holddate']
        # holddate = fac_df.loc[fac_df[f'{Label}_{Label_list[i]}'] == fac_list[i], f'{Label}_holddate']
        # print(key_list[i])

        fac_dict[key_list[i]] = [df_code, date, int(holddate)]

    # print(df_code)
    print(f'统计股票数量：{int(stock_num)}个；\n'
          f'策略历史总交易次数：{int(trades)}次；\n'
          f'策略历史平均利润：{round(earnings, 2)}%；\n'
          f'策略历史平均胜率：{round(success, 2)}%；\n'
          f'策略历史最大利润：{round(maxearnings, 2)}%，为：{fac_dict['maxearnings'][0]}；\n'
          f'策略历史最大亏损：{round(minearnings, 2)}%，为：{fac_dict['minearnings'][0]}；\n'
          f'策略历史最大胜率：{round(maxsuccess, 2)}%，为：{fac_dict['maxsuccess'][0]}；\n'
          f'策略历史最小胜率：{round(minsuccess, 2)}%，为：{fac_dict['minsuccess'][0]}；\n'
          f'策略历个股单次最大利润：{round(maxprofit, 2)}%，为：{fac_dict['maxprofit'][0]}，出现在{fac_dict['maxprofit'][1]}，持股{fac_dict['maxprofit'][2]}天；\n'
          f'策略历个股单次最大回撤:{round(maxdrawdown, 2)}%，为：{fac_dict['maxdrawdown'][0]}，出现在{fac_dict['maxdrawdown'][1]}，持股{fac_dict['maxdrawdown'][2]}天；\n'
          f'策略历个股最大连胜:{int(winstreak)}次，为：{fac_dict['winstreak'][0]}；\n'
          f'策略历个股最大连负次数:{int(losestreak)}次，为：{fac_dict['losestreak'][0]}；\n'
          f'策略历个股最大连续盈利:{round((1-profitstreak)*100, 2)}%，为：{fac_dict['profitstreak'][0]}；\n'
          f'策略历个股最大连续亏损:{round((1-drawdownstreak)*100, 2)}%。为：{fac_dict['drawdownstreak'][0]}；')


def create_code_json():
    a = ak.stock_sh_a_spot_em()['代码'].tolist()
    b = ak.stock_sz_a_spot_em()['代码'].tolist()
    c = ak.stock_bj_a_spot_em()['代码'].tolist()
    stock_list = a + b + c
    js = {'code': stock_list}
    with open(f'./stock_codes.json', 'w') as json_file:
        json.dump(js, json_file)


# 执行股票数据更新
if __name__ == '__main__':
    print("欢迎使用东哥量化工具箱\n关注各平台@东哥量化\n东哥量化，带你走上量化之路。\n")

    # inquire_code('ek', num=-1)

    # show_data(codes=['688244'])
    tick = ak.stock_zh_a_tick_tx_js(symbol="sz000001")
    print(tick)